#include <stdio.h>
#include <assert.h>  
#include <stdlib.h>
#include <iostream>  
#include "leveldb/db.h"  
#include "leveldb/options.h"
#include "leveldb/cache.h"
  
using namespace std;  
  
void* put_thread(void* in_pv);
void* get_thread(void* in_pv);
typedef struct _stValue
{
	int m_i_a;
	int m_i_b;
	int m_i_c;
	int m_i_d;
}TValue;

leveldb::DB* db = NULL;

int main(int argc,char * argv[])  
{  
	leveldb::Options options;

	options.block_cache = leveldb::NewLRUCache(30*1024*1024);
	options.create_if_missing = true;

	leveldb::Status status = leveldb::DB::Open(options, "testdb", &db);
	assert(status.ok());

  pthread_t tht_put[20];
  pthread_t tht_get[20];
  for(int i = 0; i < 20; i++)
  {
    pthread_create(&tht_put[i], NULL, put_thread, (void*)&i);
    pthread_create(&tht_get[i], NULL, get_thread, (void*)&i);
    usleep(2000);
  }

  while(1)
  {
    sleep(1);
  }

	delete db;
	delete options.block_cache;
	return 0;  
}  

void* put_thread(void* in_pv)
{
    int id = *(int*)in_pv;
    printf("[%d]put thread start!\n", id);
    leveldb::WriteOptions write_opt;
    write_opt.sync = false;
    char szKey[128] = {0};

    int tmp = 0;
    time_t start = time(NULL);
    for(int i = 0; i < 1000000; i++)
    {
      snprintf(szKey, 128, "%d_%d", id, i);
      db->Put(write_opt,
                  szKey,
                  leveldb::Slice(szKey, 128));
      time_t end = time(NULL);
      if (end - start != 0)
      {
        printf("thread[%d] put [%d] in one seconds\n",id, i - tmp);
        start = end;
        tmp = i;
      }
    }
    return NULL;
}

void* get_thread(void* in_pv)
{
    sleep(20);
    int id = *(int*)in_pv;
    leveldb::WriteOptions write_opt;
		std::string value;
    char szKey[128] = {0};
    leveldb::ReadOptions read_opt;
    read_opt.fill_cache = true;

    int tmp = 0;
    time_t start = time(NULL);
    for(int i = 0; i < 1000000; i++)
    {
      snprintf(szKey, 128, "%d_%d", id, i);
      db->Get(read_opt, szKey, &value);
      time_t end = time(NULL);
      if (end - start != 0)
      {
        printf("thread[%d] get [%d] in one seconds\n",id, i - tmp);
        start = end;
        tmp = i;
      }
      if (0 == value.size())
      {
        printf("get thread [%d] stop\n", id);
        break;
      }
    }

    return NULL;
}
